package de.gwtprime.client.presenter;

import com.google.web.bindery.requestfactory.shared.Receiver;

import de.gwtprime.client.ClientFactory;
import de.gwtprime.client.PrimeRequestFactory;
import de.gwtprime.client.event.VoteQuestionLoadedEvent;
import de.gwtprime.client.event.handler.VoteQuestionLoadedEventHandler;
import de.gwtprime.client.widgets.ArticleSectionControlWidgetInterface;
import de.gwtprime.shared.VoteType;
import de.gwtprime.shared.requestFactory.QuestionProxy;
import de.gwtprime.shared.requestFactory.VoteQuestionProxy;
import de.gwtprime.shared.requestFactory.request.QuestionRequest;

public class VoteControlPresenterQuestionImpl extends VoteControlPresenterAbstract {



	protected QuestionProxy question;

	public VoteControlPresenterQuestionImpl(QuestionProxy question,
			ClientFactory clientFactory, ArticleSectionControlWidgetInterface controlWidget){


		super(clientFactory, controlWidget, question.getUser());

		
		setVoteValue(question.getVoteValue());
		
		this.question = question;
	}


	@Override
	public void voteUp() {

		super.voteUp();
		final PrimeRequestFactory requestFactory = clientFactory.getRequestFactory();
		QuestionRequest request = requestFactory.questionRequest();

		VoteQuestionProxy vote = request.create(VoteQuestionProxy.class);
		vote.setType(VoteType.UP);


		request.addVoteAndPersist(vote, clientFactory.getUser()).using(question).fire(new Receiver<Void>() {

			@Override
			public void onSuccess(Void response) {}
		});

	}

	@Override
	public void voteDown() {

		super.voteDown();

		final PrimeRequestFactory requestFactory = clientFactory.getRequestFactory();
		QuestionRequest request = requestFactory.questionRequest();

		VoteQuestionProxy vote = request.create(VoteQuestionProxy.class);
		vote.setType(VoteType.DOWN);

		request.addVoteAndPersist(vote, clientFactory.getUser()).using(question).fire(new Receiver<Void>() {

			@Override
			public void onSuccess(Void response) {}
		});

	}

	@Override
	public void initializeListeners() {
		clientFactory.getEventBus().addHandler(VoteQuestionLoadedEvent.TYPE, new VoteQuestionLoadedEventHandler() {

			private void onVotesLoaded(
					final QuestionProxy articleSection,
					VoteQuestionLoadedEvent event) {
				VoteQuestionProxy vote =  event.getVote();

				// Disable vote buttons if vote is already applied
				voteType = vote.getType();
				if(vote.getType()==VoteType.DOWN){
					setVoteDownBtnActiveOnUI();
				}

				else if(vote.getType()==VoteType.UP){
					setVoteUpBtnActiveOnUI();

				}
			}

			@Override
			public void onVotesLoaded(VoteQuestionLoadedEvent event) {
				onVotesLoaded(question, event);
				
			}
		});

	}

}
